<?php
include("./config.php");
include("./utils.php");
?>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>范氏族谱</title>
  <?php include 'scripts-inc.php' ?>
  
  <script>


  
  var id = "<?php echo getFromMap($_GET, 'id', 50000); ?>";
  var gDepth = "<?php echo getFromMap($_GET, 'depth', 1); ?>";
  var gData ={};

  $(function(){
    
    addListeners();
joint.shapes.org.Member.prototype.markup = [
    '<g class="rotatable">',
    '<g class="scalable">',
    '<rect class="card"/><image/>',
    '</g>',
    '<text class="rank"/><text class="name"/>',
    '<g class="btn del"><text class="del">父</text></g>',
    '<g class="btn star"><text class="star">子</text></g>',
    '<g class="btn edit hide"><rect class=""/><text class="edit">编辑</text></g>',
    '</g>'
].join('');

var member = function(rank, name, image, background, textColor) {

    textColor = textColor || "#000";

    var cell = new joint.shapes.org.Member({
        size: { width: 220, height: 90 },
        attrs: {
            '.card': { fill: background, 'stroke-width': 0 },
            image: { 'xlink:href': image, 'ref-y': 10, opacity: 0.7 },
            '.rank': { fill: textColor, text: '', 'font-size': 13, 'text-decoration': 'none', 'ref-x': 0.95, 'ref-y': 0.5, 'y-alignment': 'middle', 'word-spacing': '-5px', 'letter-spacing': 0 },
            '.name': { fill: textColor, text: '', 'ref-x': 0.95, 'ref-y': 0.62, 'font-family': 'Arial' },
            '.btn.star': { 'ref-dx': -15,'ref-y': 15, 'ref': '.card' },
            '.btn.del': { 'ref-dx': -45,'ref-y': 15, 'ref': '.card' },
            '.btn.edit': { 'ref-dx': -140,'ref-y': 5, 'ref': '.card' },
            '.btn>circle': { r: 10, fill: 'transparent', stroke: '#333', 'stroke-width': 1 },
            '.btn>rect': { height: 20, width: 45, rx: 2, ry: 2, fill: 'transparent', 'stroke-width': 1 },
            '.btn.star>text': { fill: textColor,'font-size': 15, 'font-weight': 200, stroke: "#000", x: -6.5, y: 8, 'font-family': 'Times New Roman' },
            '.btn.del>text': { fill: textColor,'font-size': 15, 'font-weight': 200, stroke: "#000", x: -4.5, y: 8, 'font-family': 'Times New Roman' },
            '.btn.edit>text': { fill: textColor,'font-size': 15, 'font-weight': 500, stroke: "#000", x: 5, y: 15, 'font-family': 'Sans Serif' }
        }
    }).on({
        'change:name': function(cell, name) {
            cell.attr('.name/text', joint.util.breakText(name, { width: 160, height: 45 }, cell.attr('.name')));
        },
        'change:rank': function(cell, rank) {
            cell.attr('.rank/text', joint.util.breakText(rank, { width: 165, height: 45 }, cell.attr('.rank')));
        }
    }).set({
        name: name,
        rank: rank
    });

    return cell;
};

function link(source, target) {

    var cell = new joint.shapes.org.Arrow({
        source: { id: source.id },
        target: { id: target.id }
    });

    return cell;
}

// 将数据one和cellView连接起来 
function connectOne(one, count_map, isParent, graph, graphLayout, model){

    gData[one.id]=one;
    var sex_img = (one.sex != 'F') ? './css/images/male.png' : './css/images/female.png';
    var the_name = one.name;
    if (count_map[one.id]){
      the_name = the_name+'('+count_map[one.id]+')';
    }else{
      the_name = the_name+'(0)';
    }
    var generation = one.id + ' 第'+one.generation+'代';
    var c = getColorByGeneration(one.generation);
    var node = member(generation, the_name, sex_img, c).position(1,3);


    var newConnection = link(node, model);
    if(!isParent){
        newConnection = link(model, node)
    }
    graph.addCells([node, newConnection]);
    graphLayout.prepare().layout();
    return node;

}

	show_msg("#msg", "正在载入中...");
    var u = 'query.php?op=family&depth='+gDepth+'&id='+id;
    $.ajax({url:u,
      dataType:"json",
      async:true,
      success : function(msg, textStatus) { 

        var members = [];
        var member_map = {};
        var connections = [];

        var one = msg['one'][0];

        var sex_img = (one.sex != 'F') ? './css/images/male.png' : './css/images/female.png';
        var the_name = one.name;
        var generation = one.id + ' 第'+one.generation+'代';
        var c = getColorByGeneration(one.generation);
        var root = member(generation, the_name, sex_img, c).position(1,3);
        
        //members.push(root);
        member_map[one.id] = root;



        var sons = msg['sons-with-depth'];
        var count_list = msg['sons-with-depth-count'];

        var count_map = {};
        for(var i in count_list){
          var count_data = count_list[i];
          var k = count_data.id;
          var v = count_data.count;
          count_map[k] = v;
        }

        for(var i in sons){
            var one = sons[i];
            gData[one.id] = one;
            sex_img = (one.sex != 'F') ? './css/images/male.png' : './css/images/female.png';
            var the_name = one.name;
            if (count_map[one.id]){
              the_name = the_name+'('+count_map[one.id]+')';
            }else{
              the_name = the_name+'(0)';
            }
            var generation = one.id + ' 第'+one.generation+'代';
            var c = getColorByGeneration(one.generation);
            var son_node = member(generation, the_name, sex_img, c).position(1,3);

            member_map[one.id] = son_node;
        }

        for (var i in sons){
            var one = sons[i];
            var son_node = member_map[one.id];
            var parent_node = member_map[one.parentid];
            members.push(son_node);

            if(son_node && parent_node){
                var newConnection = link(parent_node, son_node);
                connections.push(newConnection);
            }

        }



    var graph = new joint.dia.Graph();
    var paper = new joint.dia.Paper({
        width: 1000,
        height: 1000,
        gridSize: 1,
        model: graph,
        interactive: false,
        defaultLink: new joint.shapes.org.Arrow()
    });

    var paperScroller = new joint.ui.PaperScroller({
        paper: paper,
        autoResizePaper: true
    });

    paper.on('blank:pointerdown', paperScroller.startPanning);
    paperScroller.$el.css({'padding-left': '489px', 'padding-top': '231px', 
        width: '100%', height: '100%' }).appendTo('#paper');

    graph.resetCells(members.concat(connections));

    var graphLayout = new joint.layout.TreeLayout({
        graph: graph,
        direction: 'R'
    });

    var treeLayoutView = new joint.ui.TreeLayoutView({
        paper: paper,
        model: graphLayout,
        previewAttrs: {
            //parent: { rx: 10, ry: 10 }
            parent: { rx: 0, ry: 0 }
        }
    });

    graphLayout.layout();

    paperScroller.zoom(-0.4);
    $(".paper-scroller").css("padding-left","0").css("padding-top","0");
    //paperScroller.zoom(-0.2);
    //paperScroller.centerContent();

paper.on('cell:pointerup', function(cellView, evt, x, y) {

    if (V(evt.target).hasClass('star')) {
        var id = cellView.model.attributes.rank.split(' ')[0];
        var u='query.php?op=sons-list&id='+id;
        $.ajax({url:u,
          dataType:"json",
          async:true,
          success : function(msg, textStatus) {
            var sons = msg['sons'];
            var count_list = msg['sons-count'];

            var count_map = {};
            for(var i in count_list){
              var count_data = count_list[i];
              var k = count_data.id;
              var v = count_data.count;
              count_map[k] = v;
            }

            for(var i in sons){
                var one = sons[i];
                if(gData[one.id]) continue;
                connectOne(one, count_map, false, graph, graphLayout, cellView.model);


                //var one = sons[i];
                //if(gData[one.id]) continue;
                //gData[one.id]=one;
                //sex_img = (one.sex != 'F') ? './css/images/male.png' : './css/images/female.png';
                //var the_name = one.name;
                //if (count_map[one.id]){
                //  the_name = the_name+'('+count_map[one.id]+')';
                //}else{
                //  the_name = the_name+'(0)';
                //}
                //var generation = one.id + ' 第'+one.generation+'代';
                //var c = getColorByGeneration(one.generation);
                //var son_node = member(generation, the_name, sex_img, c).position(1,3);
//
//
                //var newConnection = link(cellView.model, son_node);
                //graph.addCells([son_node, newConnection]);
                //graphLayout.prepare().layout();
            }
            
            //V(evt.target).addClass('hide');
            //V(evt.target).sibling('del').removeClass('hide');
        }

        });

    } else if (V(evt.target).hasClass('del')) {
        var id = cellView.model.attributes.rank.split(' ')[0];
        //id = parseInt(id);
        if(!gData[id]) return;
        id = gData[id].parentid;

        var u='query.php?op=family&id='+id;
        $.ajax({url:u,
          dataType:"json",
          async:true,
          success : function(msg, textStatus) {
            if(!msg || !msg.one) return;
            var one = msg['one'][0];
            var sons = msg['sons-with-depth']
            var count_list = msg['sons-with-depth-count'];
            var count_map = {};
            count_map[msg['one-count'][0].id] = msg['one-count'][0].count;
            var parent_node = connectOne(one, count_map, true, graph, graphLayout, cellView.model);


            for(var i in count_list){
              var count_data = count_list[i];
              var k = count_data.id;
              var v = count_data.count;
              count_map[k] = v;
            }

            for(var i in sons){
                var one = sons[i];
                if(gData[one.id]) continue;
                connectOne(one, count_map, false, graph, graphLayout, parent_node);
            }
            $(".paper-scroller").css("padding-left","0").css("padding-top","0");

            }
        });

        //cellView.model.remove();
        //graphLayout.prepare().layout();

    } else if (V(evt.target).hasClass('edit')) {

        var inspector = new joint.ui.Inspector({
            inputs: {
                'rank': {
                    type: 'text',
                    label: 'Rank',
                    index: 1
                },
                'name': {
                    type: 'text',
                    label: 'Name',
                    index: 2
                },
                'attrs/image/xlink:href': {
                    type: 'select',
                    label: 'Sex',
                    options: [
                        { value: './css/images/male.png', content: 'Male' },
                        { value: './css/images/female.png', content: 'Female' }
                    ],
                    index: 3
                },
                'attrs/.card/fill': {
                    type: 'color-palette',
                    label: 'Color',
                    index: 5,
                    options: [
                        { content: '#31d0c6' },
                        { content: '#7c68fc' },
                        { content: '#fe854f' },
                        { content: '#feb663' },
                        { content: '#c6c7e2' }
                    ]
                }
            },
            cellView: cellView
        });

        var dialog = new joint.ui.Dialog({
            width: 250,
            title: 'Edit Member',
            content: inspector.render().el
        });

        dialog.on('action:close', inspector.remove, inspector);
        dialog.open();
		show_msg("#msg", "载入完成！");
    }
});

var directionPicker = new joint.ui.SelectBox({
    width: 150,
    options: [
        { value: 'L', content: 'Right-Left' },
        { value: 'R', content: 'Left-Right' },
        { value: 'T', content: 'Bottom-Top' },
        { value: 'B', content: 'Top-Bottom', selected: true},
    ]
}).on('option:select', function(option) {
    _.invoke(graph.getElements(), 'set', 'direction', option.value);
    graphLayout.layout();
    //paperScroller.centerContent();
});

$('#orgchart-direction').append(directionPicker.render().el);



      }
    },"text");


  });//end of $(function(){
  </script>
</head>
<body>

<div id="wrapper">
<div id="container">

<div id="nav_data_src">
  <?php include 'navbars-inc.php' ?>
</div>

<div id="search-result">
</div>
<div id="msg">
</div>


<div class="" style="text-align:center;">
<div class="col-xs-12 col-sm-12 col-md-12" style="">
<div classs="example">
    <div id="paper" class="paper"></div>
    <p class="hide">Show the ORG Chart in  <span id="orgchart-direction"></span> direction. </p>
</div><!--end example-->
</div><!--end scroll-->
</div><!--end scroll-->

<div class="clearfix"></div>
</div><!-- end of search-container -->


<!-- .................................................... -->
</div><!-- end of container -->
</div><!-- end of wrapper -->
<div id="hide-result"> </div>
</body>
</html>
